package handlers

import (
	"book-flag-novel/cache"
	"book-flag-novel/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var books []models.Book
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&books)
		jsonData, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &books)
	}
	var total int64
	models.DB.Model(&models.Book{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  books,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var book models.Book
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Debug().Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": book,
	})
	return
}
